package nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;

/**
 * @ClassName NioDiscardServer
 * @Description TODO
 * @Author leejiliang
 * @DateTime 2021/8/27 14:24
 * @Version 1.0
 */
public class NioDiscardServer {
    public static void startServer() throws Exception {
        var selector = Selector.open();
        var serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(1989));
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (selector.select() > 0) {
            var keyIterator = selector.selectedKeys().iterator();
            while (keyIterator.hasNext()) {
                var selectionKey = keyIterator.next();
                if (selectionKey.isAcceptable()) {
                    var socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);

                } else if (selectionKey.isReadable()) {
                    var channel = (SocketChannel) selectionKey.channel();
                    var buff = ByteBuffer.allocate(1024);
                    while (channel.read(buff) > 0) {
                        buff.flip();
                        System.out.println(new String(buff.array(), 0, buff.limit()));
                        buff.clear();
                    }
                    channel.close();
                }
                keyIterator.remove();
            }
        }
        serverSocketChannel.close();
    }

    public static void main(String[] args) throws Exception {
        startServer();
    }
}
